#!/bin/bash
#
# CIDI Front Panel LED Control
#

function usage()
{
	echo -e "\nUsage: $0 <led_no> [on/off]"
	echo -e "  led_no --- LED No in Front Panel, should be 1, 2, 3, 4"
	echo -e "  on/off --- Turn on or off the LED\n"
}

if [[ $# -lt 1 ]]; then
	usage
	exit 1
fi

if [[ $(id -u) -ne 0 ]]; then
    echo -e "\nERROR: please run as root\n"
    exit 1
fi

declare -A GPIO_NUM_ARRAY
# 414/338/412/413
GPIO_NUM_ARRAY[1]=414
GPIO_NUM_ARRAY[2]=338
GPIO_NUM_ARRAY[3]=413
GPIO_NUM_ARRAY[4]=412

LED_NO=$1
SYSFS_GPIO=/sys/class/gpio
SYSFS_GPIO_NUM=${SYSFS_GPIO}/gpio${GPIO_NUM_ARRAY[${LED_NO}]}

if [[ ! ${LED_NO} =~ ^[1-4]$ ]]; then
	usage
	exit 1
fi

# GPIO Init
if [[ ! -d ${SYSFS_GPIO_NUM} ]]; then
	echo ${GPIO_NUM_ARRAY[${LED_NO}]} > ${SYSFS_GPIO}/export
	echo "out" > ${SYSFS_GPIO_NUM}/direction
	echo "0"   > ${SYSFS_GPIO_NUM}/active_low
fi

if [[ $# -eq 1 ]]; then
	# GPIO GET
	GPIO_VALUE=$(cat ${SYSFS_GPIO_NUM}/value)
	if [[ ${GPIO_VALUE} == 0 ]]; then
		echo "LED ${LED_NO}, OFF"
	else
		echo "LED ${LED_NO}, ON"
	fi
else
	# GPIO SET
	if [[ $2 == "ON" || $2 == "on" ]]; then
		echo 1 > ${SYSFS_GPIO_NUM}/value
		echo "LED ${LED_NO}, ON"
	elif [[ $2 == "OFF" || $2 == "off" ]]; then
		echo 0 > ${SYSFS_GPIO_NUM}/value
		echo "LED ${LED_NO}, OFF"
	else
		usage
		exit 1
	fi
fi
